package rwheel

import (
	"context"
	"fmt"
	"time"
)

// AddTickerFunc 加入一个计时任务
func AddTickerFunc(key string, fx Func, ctx *context.Context, d time.Duration) error {
	_lockTickerMap.Lock()
	defer _lockTickerMap.Unlock()
	if _, ok := _tickerMap[key]; ok {
		return fmt.Errorf("【%v】已存在", key)
	}
	if ctx == nil {
		background := context.Background()
		ctx = &background
	}
	_tickerMap[key] = &_tickerFunc{
		key:         key,
		ctx:         ctx,
		fx:          fx,
		interval:    d,
		nextRunTime: time.Now().Add(d).UnixMilli(),
	}
	return nil
}

// ResetTickerFunc 重置指定的计时任务
func ResetTickerFunc(key string, d time.Duration) error {
	_lockTickerMap.Lock()
	defer _lockTickerMap.Unlock()
	if v, ok := _tickerMap[key]; false == ok {
		return fmt.Errorf("【%v】不存在", key)
	} else {
		v.nextRunTime = time.Now().Add(d).UnixMilli()
		v.interval = d
		return nil
	}
}

// RemoveTickerFunc 移除指定的计时任务
func RemoveTickerFunc(key string) {
	_lockTickerMap.Lock()
	defer _lockTickerMap.Unlock()
	delete(_tickerMap, key)
}

// SetParamsTickerFunc 设置指定的计时任务的Context的key-value
func SetParamsTickerFunc(key string, pKey any, pValue any) error {
	_lockTickerMap.Lock()
	defer _lockTickerMap.Unlock()
	if v, ok := _tickerMap[key]; false == ok {
		return fmt.Errorf("【%v】不存在", key)
	} else {
		value := context.WithValue(*v.ctx, pKey, pValue)
		v.ctx = &value
		return nil
	}
}

// RangeTickerFunc 获取当前所有的计时器函数信息
func RangeTickerFunc() []FuncName {
	_lockTickerMap.Lock()
	defer _lockTickerMap.Unlock()
	var rt = make([]FuncName, 0, 10)
	for k, v := range _tickerMap {
		rt = append(rt, FuncName{
			Key:      k,
			RunTime:  v.nextRunTime,
			Interval: v.interval,
		})
	}
	return rt
}
